#!/usr/bin/env python
"""
# -*- coding: utf-8 -*-
# @Time    : 2020/9/30 17:09
# @Author  : AshJo
# @Desc    : 服务端
# @Filename: server.py
# @Version : v1.0
"""

# 接收文件
import socket
import json
import struct
import os
import hmac


secret_key = b'ashjo_233'
sk = socket.socket()
sk.bind(('127.0.0.1', 9000))

sk.listen()
conn, addr = sk.accept()

"""验证客户端合法性"""
# 发送随机字符串给客户端
rand = os.urandom(32)
conn.send(rand)

# server自身的摘要计算
h = hmac.new(secret_key, rand)
ret = h.digest()

# 接受返回结果，进行摘要结果的比对
res = conn.recv(1024)

if res == ret:
    msg_len = conn.recv(4)
    dic_len = struct.unpack('i', msg_len)[0]
    msg = conn.recv(dic_len).decode('utf-8')
    msg = json.loads(msg)

    """接收小文件"""
    # with open(msg['filename'], mode='wb') as f:
    #     content = conn.recv(msg['filesize'])
    #     print('--->', len(content))
    #     f.write(content)
    """接收大文件"""
    with open(msg['filename'], mode='wb') as f:
        while msg['filesize'] > 0:
            content = conn.recv(1024)
            msg['filesize'] -= len(content)
            f.write(content)

    conn.close()
    sk.close()


else:
    conn.close()
